/* eslint-disable no-continue */
/*
 * @Author: liuyonghu
 * @Date: 2022-08-12 17:13:17
 * @LastEditTime: 2022-08-12 17:22:40
 * @LastEditors: liuyonghu
 * @Description: request ulits
 * @FilePath: /prc_customer_mdm_front/src/requests/utils.ts
 */

const nullVals = ["", null];

function isNull(val) {
    return nullVals.includes(val) || JSON.stringify(val) === "{}";
}

function getNullPath(nullKeys, keys, params, firstKey) {
    for (var index = 0; index < keys.length; index += 1) {
        var key = keys[index];
        var val = params[key];
        var keyPath = firstKey
            ? "".concat(firstKey, ",").concat(key)
            : "".concat(key);
        // debugger;
        if (isNull(val)) {
            var keyObj = nullKeys.find(function (it) {
                return it.key === keyPath;
            });
            if (!keyObj) {
                nullKeys.push({
                    key: keyPath,
                });
            }
            continue;
        }
        if (Object.prototype.toString.call(val) === "[object Object]") {
            var subKeys = Object.keys(val);
            debugger;
            if (subKeys.length > 0) {
                getNullPath(nullKeys, subKeys, val, keyPath);
            } else {
                nullKeys.push({
                    key: keyPath,
                });
            }
        }
    }
}
function getAllNullKeys(params) {
    var keys = Object.keys(params);
    var nullKeys = [];
    if (keys.length > 0) {
        getNullPath(nullKeys, keys, params, "");
    }
    return nullKeys;
}

function getValByPath(params, pathObj) {
    var keys = pathObj.key.split(",");
    var obj = params;
    for (var i = 0; i < keys.length; i += 1) {
        var key = keys[i];
        if (i === keys.length - 1) {
            return obj[key];
        }
        obj = obj[key];
    }
}
function deleteNullByPath(params, pathObj) {
    var keys = pathObj.key.split(",");
    var obj = params;
    for (var i = 0; i < keys.length; i += 1) {
        var key = keys[i];
        if (i === keys.length - 1) {
            delete obj[key];
            continue;
        }
        obj = obj[key];
    }
}

function handleNullByPath(params, pathObj) {
    console.log(pathObj);
    deleteNullByPath(params, pathObj);
    var keys = pathObj.key.split(",");
    if (keys.length > 1) {
        keys.pop();
        const nexKey = keys.join(",");
        const val = getValByPath(params, { key: nexKey });
        if (isNull(val)) {
            handleNullByPath(params, { key: nexKey });
        }
    }
}
export function deleteNull(params) {
    var nullPaths = getAllNullKeys(params);
    // debugger;
    for (var index = 0; index < nullPaths.length; index += 1) {
        const keyPath = nullPaths[index];
        handleNullByPath(params, keyPath);
    }
}
export default { deleteNull: deleteNull };
